package com.caption.auth.secuity.sms;

import com.caption.auth.model.entity.SysRole;
import com.caption.auth.model.entity.SysUser;
import com.caption.auth.secuity.constant.SecurityConstant;
import com.caption.auth.secuity.entity.SysUserDetails;
import com.caption.auth.service.SysUserService;
import com.caption.core.model.enums.BaseResultEnum;
import com.caption.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * @description: 通过手机号验证码获取用户信息
 * @author: 码农
 * @date: 2021-12-31 20:15:12
 */
@Component
@Slf4j
public class SmsCodeDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
  /*  @Autowired
    private RedisUtils redisUtils;
*/
    @Override
    public SysUserDetails loadUserByUsername(String mobile) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();
        String smsCode = request.getParameter(SecurityConstant.SMS_CODE);
        String loginType = request.getParameter(SecurityConstant.LOGIN_TYPE);
        if (StringUtils.isAnyBlank(smsCode, loginType)) {
            throw new ServiceException(BaseResultEnum.MISSING_REQUIRED_ARGUMENTS);
        }
        SysUser sysUser = sysUserService.selectByPhone(mobile);
        if (Objects.isNull(sysUser)) {
            throw new UsernameNotFoundException("用户不存在");
        }

        String mobile_key = SecurityConstant.SMS_CODE_DB_PREFIX + mobile;
        String dbSmsCode = "6666";
                //redisUtils.getString(mobile_key);
        if (!StringUtils.equals(dbSmsCode, smsCode)) {
            throw new BadCredentialsException("验证码错误");
        }

        SysUserDetails sysUserDetails = new SysUserDetails();
        BeanUtils.copyProperties(sysUser, sysUserDetails);
        List<SysRole> sysRoles = sysUserService.selectRoleByUserId(sysUser.getId());
        sysUserDetails.setRoles(sysRoles);
        return sysUserDetails;
    }
}
